/**
 * 多图上传组件
 * 提供多图上传、预览、删除、放大查看等功能
 * @author CodeBuddy
 */

// 全局样式，只需加载一次
(function() {
    // 如果已经添加过样式，则不再添加
    if (document.getElementById('image-uploader-styles')) {
        return;
    }
    
    const style = document.createElement('style');
    style.id = 'image-uploader-styles';
    style.textContent = `
        /* 模态框样式 */
        .image-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            overflow: auto;
        }
        
        .modal-content {
            margin: auto;
            display: block;
            max-width: 90%;
            max-height: 90%;
            margin-top: 2%;
        }
        
        .modal-close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .image-preview-item {
            position: relative;
            margin: 5px;
            width: 100px;
            height: 100px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .image-preview-item:hover {
            transform: scale(1.05);
        }
        
        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .image-preview-item .delete-btn {
            position: absolute;
            top: 0;
            right: 0;
            background: rgba(255, 0, 0, 0.7);
            color: white;
            border: none;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            cursor: pointer;
            font-size: 12px;
            z-index: 10;
        }
        
        .file-preview-item {
            position: relative;
            margin: 5px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            width: 250px;
            background-color: #f9f9f9;
        }
        
        .file-preview-item .file-name {
            margin-right: 10px;
            max-width: 180px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    `;
    document.head.appendChild(style);
    
    // 创建模态框，如果不存在
    if (!document.getElementById('imageModal')) {
        const modal = document.createElement('div');
        modal.id = 'imageModal';
        modal.className = 'image-modal';
        modal.innerHTML = `
            <span class="modal-close">&times;</span>
            <img class="modal-content" id="modalImage">
        `;
        document.body.appendChild(modal);
        
        // 关闭模态框
        modal.querySelector('.modal-close').onclick = function() {
            modal.style.display = "none";
        };
        
        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        });
    }
})();

/**
 * 图片上传器类
 */
class ImageUploader {
    /**
     * 创建图片上传器实例
     * @param {Object} options 配置选项
     * @param {string} options.inputId 文件输入框的ID
     * @param {string} options.previewContainerId 预览容器的ID
     * @param {string} options.fieldName 字段名称，用于表单提交
     * @param {Array} [options.existingImages] 已存在的图片数组
     * @param {boolean} [options.useDataTransfer=true] 是否使用DataTransfer API管理文件
     */
    constructor(options) {
        this.inputId = options.inputId;
        this.previewContainerId = options.previewContainerId;
        this.fieldName = options.fieldName;
        this.existingImages = options.existingImages || [];
        this.useDataTransfer = options.useDataTransfer !== false;
        
        this.fileInput = document.getElementById(this.inputId);
        this.previewContainer = document.getElementById(this.previewContainerId);
        
        if (!this.fileInput || !this.previewContainer) {
            console.error('ImageUploader: 找不到输入框或预览容器');
            return;
        }
        
        // 如果使用DataTransfer API
        if (this.useDataTransfer) {
            this.fileStore = new DataTransfer();
        }
        
        this.init();
    }
    
    /**
     * 初始化上传器
     */
    init() {
        // 绑定文件选择事件
        this.fileInput.addEventListener('change', this.handleFileSelect.bind(this));
        
        // 渲染已存在的图片
        this.renderExistingImages();
    }
    
    /**
     * 渲染已存在的图片
     */
    renderExistingImages() {
        if (!this.existingImages || !this.existingImages.length) {
            return;
        }
        
        this.existingImages.forEach((src, index) => {
            const div = document.createElement('div');
            div.className = 'image-preview-item';
            div.innerHTML = `
                <img src="${src}" alt="" onclick="ImageUploader.showImageModal('${src}')">
                <button type="button" class="delete-btn" title="删除">×</button>
                <input type="hidden" name="old_${this.fieldName}[]" value="${src}">
            `;
            
            // 添加删除按钮事件
            div.querySelector('.delete-btn').addEventListener('click', (event) => {
                event.stopPropagation(); // 阻止事件冒泡
                
                if (confirm('确定要删除这张图片吗？')) {
                    // 移除图片元素
                    this.previewContainer.removeChild(div);
                    
                    // 创建一个隐藏的输入字段，用于告诉后端删除这个图片
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = `remove_${this.fieldName}[]`;
                    input.value = src;
                    document.querySelector('form').appendChild(input);
                    
                    // 调试信息
                    console.log('删除图片:', src);
                }
            });
            
            this.previewContainer.appendChild(div);
        });
    }
    
    /**
     * 处理文件选择
     * @param {Event} e 事件对象
     */
    handleFileSelect(e) {
        const files = e.target.files;
        
        // 如果使用DataTransfer API，先清空文件存储
        if (this.useDataTransfer) {
            this.fileStore = new DataTransfer();
        }
        
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            
            // 如果使用DataTransfer API，添加文件到存储
            if (this.useDataTransfer) {
                this.fileStore.items.add(file);
            }
            
            if (file.type.startsWith('image/')) {
                this.createImagePreview(file, i);
            }
        }
        
        // 如果使用DataTransfer API，更新文件输入框的文件列表
        if (this.useDataTransfer) {
            this.fileInput.files = this.fileStore.files;
        }
    }
    
    /**
     * 创建图片预览
     * @param {File} file 文件对象
     * @param {number} index 文件索引
     */
    createImagePreview(file, index) {
        const reader = new FileReader();
        const self = this;
        
        reader.onload = function(e) {
            const div = document.createElement('div');
            div.className = 'image-preview-item';
            div.dataset.index = index; // 存储文件索引
            
            div.innerHTML = `
                <img src="${e.target.result}" alt="${file.name}">
                <button type="button" class="delete-btn" title="删除">×</button>
            `;
            
            // 添加删除按钮事件
            div.querySelector('.delete-btn').addEventListener('click', function(event) {
                event.stopPropagation(); // 阻止事件冒泡
                
                if (confirm('确定要删除这张图片吗？')) {
                    // 移除图片元素
                    self.previewContainer.removeChild(div);
                    
                    // 如果使用DataTransfer API，从文件存储中移除文件
                    if (self.useDataTransfer) {
                        const index = parseInt(div.dataset.index);
                        const newFileList = new DataTransfer();
                        
                        for (let j = 0; j < self.fileStore.files.length; j++) {
                            if (j !== index) {
                                newFileList.items.add(self.fileStore.files[j]);
                            }
                        }
                        
                        self.fileStore = newFileList;
                        self.fileInput.files = self.fileStore.files;
                    }
                }
            });
            
            // 添加点击放大事件
            div.addEventListener('click', function() {
                ImageUploader.showImageModal(e.target.result);
            });
            
            self.previewContainer.appendChild(div);
        };
        
        reader.readAsDataURL(file);
    }
    
    /**
     * 显示图片模态框
     * @param {string} src 图片源
     */
    static showImageModal(src) {
        const modal = document.getElementById('imageModal');
        const modalImg = document.getElementById('modalImage');
        modal.style.display = "block";
        modalImg.src = src;
    }
}

// 导出组件
window.ImageUploader = ImageUploader;